#!/usr/bin/env python

import sys
from xml.dom import minidom

import gbase
import getpass
from xml_helper import *
import gbase_template
from base64 import b64encode, b64decode
import pickle

service = None

class PersistentException(Exception):
    def __init__(self):
        Exception.__init__(self)

def init(conf):
	global service
	proxy_conf = conf.get('proxy', None)
	if proxy_conf:
		gbase.PROXY_HOST = proxy_conf.get('host', '')
		gbase.PROXY_PORT = proxy_conf.get('port', None)

	username = conf.get('jid').split('/', 1)[0]
	passwd = conf.get('passwd')
	if service:
		pass
	else:
		service = gbase.GoogleBaseService(username, passwd)
        service.ProgrammaticLogin()

def make_data(title, content, filename):
    return gbase_template.TEMP_NOTES % (title, content, filename)

def LoadObjbyName(objname):
    try:
        #service = gbase.GoogleBaseService(username, passwd)
        #service.ProgrammaticLogin()
        feed = service.loadObjStr(objname)
        try:
            entries = getFeedEntries(feed)
            if len(entries) > 0:
                content = getEntryContent(entries[0])
                obj_id = getEntryID(entries[0])
                return obj_id, content 
            else:
                return None, ''
        finally:
            feed.unlink()
    except:
        raise PersistentException
        
def LoadObjbyID(obj_id):
    try:
        #service = gbase.GoogleBaseService(username, passwd)
        #service.ProgrammaticLogin()
        feed = service.loadObjbyID(obj_id)
        try:
            entries = getFeedEntries(feed)
            if len(entries) > 0:
                content = getEntryContent(entries[0])
                return content
            else:
                return ''
        finally:
            feed.unlink()
    except:
        raise PersistentException
        
def StoreObj(obj_name, content, filename=''):
    try:
        obj_data = make_data(obj_name, content, filename)
        #service = gbase.GoogleBaseService(username, passwd)
        #service.ProgrammaticLogin()
        feed, obj_id = service.insertObjStr(obj_data)
        feed.unlink()
        return obj_id
    except:
        raise PersistentException
        
def ModifyObjbyName(obj_name, content, filename=''):
    try:
        obj_id, old_content = LoadObjbyName(obj_name)
        if obj_id:
            obj_data = make_data(obj_name, content, filename)
            #service = gbase.GoogleBaseService(username, passwd)
            #service.ProgrammaticLogin()
            feed = service.updateObj(obj_id, obj_data)
            feed.unlink()
            return obj_id
        else:
            return None
    except:
        raise PersistentException

def ModifyObj(obj_id, obj_name, content, filename=''):
    try:
        #service = gbase.GoogleBaseService(username, passwd)
        #service.ProgrammaticLogin()
        obj_data = make_data(obj_name, content, filename)
        feed = service.updateObj(obj_id, obj_data)
        feed.unlink()
    except:
        raise PersistentException
        
def DelObj(obj_id):
    try:
        #service = gbase.GoogleBaseService(username, passwd)
        #service.ProgrammaticLogin()
        status = service.deleteObj(obj_id)
        return status
    except:
        raise PersistentException

def SaveObj(objname, obj):
	objstr = b64encode(pickle.dumps(obj, 2))
	objid, content = LoadObjbyName(objname)
	if None == objid:
		objid = StoreObj(objname, objstr)			
	else:
		ModifyObj(objid, objname, objstr)

	return objid

def LoadObj(objname):
	objid, content = LoadObjbyName(objname)
	obj = None
	if objid:
		try:
			obj = pickle.loads(b64decode(content))
		except:
			pass
	else:
		pass

	return obj
